package com.yrxy.thread.interview.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author huanglaoxie(微信:yfct-8888)
 * @className SemaphoreDemo
 * @description：
 * @date 2017/6/29 14:00
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        //设置信号量同时执行的线程数是4
        final Semaphore semp = new Semaphore(4);
        // 模拟20个请求
        for (int i = 0; i < 20; i++) {
            final int index = i;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        //使用acquire()获取锁
                        semp.acquire();
                        System.out.println("acquire and access: " + index);
                        //睡眠1秒
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                    }  finally {
                        //使用完成释放锁
                        semp.release();
                        System.out.println("---- release ----");
                    }
                }
            };
            exec.execute(run);
        }
        // 退出线程池
        exec.shutdown();
    }

}
